package com.example.java_gobang.api;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

/**
 * 测试的websocket接口，可忽略
 */
@Component
public class TestAPI extends TextWebSocketHandler {

    /**
     * 建立连接websocket长连接后执行
     * @param session websocket的会话
     * @throws Exception
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        System.out.println("连接成功");
    }

    /**
     * 接收到客户端websocket消息后执行
     * @param session websocket的会话
     * @param message 接收到的文本消息
     * @throws Exception
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        System.out.println("收到消息: " + message.getPayload());
        // 让服务器收到数据之后, 把数据原封不动的返回回去~
        session.sendMessage(message);
    }

    /**
     * 在出现websocket代码抛出异常时执行
     * @param session websocket的会话
     * @param exception 抛出的异常对象
     * @throws Exception
     */
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        System.out.println("连接异常");
    }

    /**
     * 在websocket长连接断开关闭时执行
     * @param session websocket的会话
     * @param status websocket关闭状态对象，包含关闭的状态码和原因
     * @throws Exception
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        System.out.println("连接关闭");
    }
}
